package model

import (
	"im-v1/database"
	"im-v1/tool"
	"time"
)

type Relationship struct {
	Id            int       `json:"id" gorm:"column:id"`                         // 自增主键
	MailFrom      string    `json:"mail_from" gorm:"column:mail_from"`           // 发起人
	MailTo        string    `json:"mail_to" gorm:"column:mail_to"`               // 接收方
	SetupTime     time.Time `json:"setup_time" gorm:"column:setup_time"`         // 发起时间
	RelationGrade int       `json:"relation_grade" gorm:"column:relation_grade"` // 关系等级
	Secret        string    `json:"secret" gorm:"column:secret"`                 // 联系密钥-唯一
}

func (e *Relationship) TableName() string {
	return "relationship"
}

// 生成新的关系
func NewRelationship(from, to string, grade int) *Relationship {
	return &Relationship{0,
		from,
		to,
		time.Now(),
		grade,
		tool.RandString(8),
	}
}

// 插入记录
func (e *Relationship) InsertRelationship() {
	database.Db.Create(e)
}

// 判断记录存在与否
func (e *Relationship) IsAlreadyGoodFriend() (bool, *Relationship) {
	r := &Relationship{}
	raw := database.Db.Where("mail_from = ? and mail_to = ?", e.MailFrom, e.MailTo).Find(r)
	return raw.RowsAffected != 0, r
}

// 删除记录
func DeleteFriend(from, to string) bool {
	raw := database.Db.Where("mail_from = ? and mail_to = ?", from, to).Delete(&Relationship{})
	return raw.RowsAffected != 0
}
